package notifiers

import (
	"fmt"
	"gopkg.in/gomail.v2"
	"strconv"
	"yunzhan/alert-server/internal/types"
)

/**
 * @Author: way lee
 * @Date: 2024/9/10 09:13
 * @Desc:
 */

func SendEmail(config []types.EmailConfig, contentType string, message string) error {
	if len(config) == 0 {
		return fmt.Errorf("no email configuration provided")
	}

	emailConfig := config[0]

	m := gomail.NewMessage()
	m.SetHeader("From", emailConfig.Username)
	m.SetHeader("To", emailConfig.Recipient)
	m.SetHeader("Subject", "YunFan-BigdataOps Alert Notification")
	m.SetBody(contentType, message)

	port, err := strconv.Atoi(emailConfig.Port)
	if err != nil {
		return err
	}
	d := gomail.NewDialer(emailConfig.SmtpServer, port, emailConfig.Username, emailConfig.Password)

	// 发送邮件
	if err := d.DialAndSend(m); err != nil {
		return fmt.Errorf("failed to send email notification: %w", err)
	}

	return nil
}
